package main

import (
	"fmt"
	orderconfig "gitee.com/worklz/grpc-mtls-demo/server-order/config"
	orderpb "gitee.com/worklz/grpc-mtls-demo/server-order/proto/order"
	"gitee.com/worklz/grpc-mtls-demo/server-user/config"
	"gitee.com/worklz/grpc-mtls-demo/server-user/handler"
	_ "gitee.com/worklz/grpc-mtls-demo/server-user/pkg/boot"
	"gitee.com/worklz/grpc-mtls-demo/server-user/pkg/shutdown"
	"gitee.com/worklz/grpc-mtls-demo/server-user/pkg/util"
	userpb "gitee.com/worklz/grpc-mtls-demo/server-user/proto/user"
	"google.golang.org/grpc"
	"google.golang.org/grpc/health"
	healthpb "google.golang.org/grpc/health/grpc_health_v1"
	"log"
	"net"
)

func main() {
	// 关闭处理（释放资源等）
	defer shutdown.Handle()

	// 加载服务端mTLS凭证
	creds, err := util.LoadServerMTLSCredentials()
	if err != nil {
		panic(fmt.Sprintf("加载mTLS凭证失败: %v", err))
	}

	// 监听端口
	lis, err := net.Listen("tcp", config.ServerAddr)
	if err != nil {
		panic(fmt.Sprintf("无法监听地址[%s]: %v", config.ServerAddr, err))
	}
	fmt.Printf("gRPC %s 启动成功，监听地址: 127.0.0.1%s\r\n", config.ServerDesc, config.ServerAddr)

	// 创建gRPC服务器
	s := grpc.NewServer(grpc.Creds(creds))

	// 初始化订单服务客户端的mTLS凭证（服务间调用）
	orderClientCreds, err := util.LoadClientMTLSCredentials(orderconfig.ServerName)
	if err != nil {
		log.Fatalf("创建订单服务mTLS凭证失败: %v", err)
	}
	// 生成订单服务客户端
	orderServiceConn, orderServiceConnErr := grpc.NewClient(
		orderconfig.ServerAddr,
		grpc.WithTransportCredentials(orderClientCreds),
		// 可添加其他选项，如超时设置
		// grpc.WithTimeout(5*time.Second),
	)
	defer func() {
		if closeErr := orderServiceConn.Close(); closeErr != nil {
			log.Fatalf("订单服务调用链接关闭失败！%v", closeErr)
		}
	}()
	if orderServiceConnErr != nil {
		panic(fmt.Sprintf("订单服务调用链接生成失败: %v", orderServiceConnErr))
	}
	orderServiceClient := orderpb.NewOrderServiceClient(orderServiceConn)

	// 注册用户服务
	userpb.RegisterUserServiceServer(s, handler.NewUserHandler(orderServiceClient))

	// 注册健康检查服务
	healthpb.RegisterHealthServer(s, health.NewServer())

	// 启动服务
	if err := s.Serve(lis); err != nil {
		panic(fmt.Sprintf("服务启动失败: %v", err))
	}
}
